﻿using System.Net;
using System.Threading.Tasks;
using JTTD.Common.Attribute;
using JTTD.Domain;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.CompanyUserInfo.Request;
using JTTD.Domain.Dtos.CompanyUserInfo.Response;
using JTTD.Domain.IService;
using JTTD.Extensions;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using JTTD.Domain.Dtos.WeiXin;
using JTTD.Error;

namespace JTTD.Controllers
{
    /// <summary>
    /// 管理员/店家信息
    /// </summary>
    [Route("api/companyUser")]
    [ApiController]
    public class CompanyUserController : BaseController
    {

        private readonly ICompanyUserInfoService _companyUserInfoService;

        private readonly IWeiXinService _weiXinService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="companyUserInfoService"></param>
        public CompanyUserController(ICompanyUserInfoService companyUserInfoService, IWeiXinService weiXinService)
        {
            _companyUserInfoService = companyUserInfoService;
            _weiXinService = weiXinService;
        }


        /// <summary>
        /// 店家入驻（微信公众号）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [UnAuthorize]
        [HttpPost]
        [Route("insert")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<GetCompanyUserInfoDto>))]
        public async Task<IActionResult> Insert(InsertCompanyUserInfoRequestDto model)
        {
            return Ok(await _companyUserInfoService.InsertCompanyUser(model));
        }

        /// <summary>
        /// 获取商户信息(微信公众号)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("getCompanyUserInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<GetCompanyUserInfoDto>))]
        public async Task<IActionResult> GetCompanyUserInfo()
        {
            return Ok(await _companyUserInfoService.GetCompanyUserInfoById(UserId));
        }

        /// <summary>
        /// 获取商户信息(微信公众号,普通用户查看店家)
        /// </summary>
        /// <param name="shopId">店家Id</param>
        /// <returns></returns>
        [HttpGet]
        [UnAuthorize]
        [Route("GetShopInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<GetCompanyUserInfoDto>))]
        public async Task<IActionResult> GetShopInfo(int shopId)
        {
            return Ok(await _companyUserInfoService.GetCompanyUserInfoById(shopId, UserId));
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPageList")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<PageResult<GetCompanyUserInfoDto>>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> GetPageList(SearchCompanyUserInfoDto search)
        {
            return Ok(await _companyUserInfoService.GetPageList(search));
        }

        /// <summary>
        /// 微信公众号展示审核通过的店家列表(h5)
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [UnAuthorize]
        [HttpPost]
        [Route("GetShopUserList")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<PageResult<GetShopUserDto>>))]
        public async Task<IActionResult> GetShopUserList(SearchShopRequestDto search)
        {
            var result = await _companyUserInfoService.GetShopUserList(search);
            return Ok(result);
        }

        /// <summary>
        /// 获取所有店家类型(h5)
        /// </summary>
        /// <returns></returns>
        [UnAuthorize]
        [HttpGet]
        [Route("allShopTypes")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<string[]>))]
        public async Task<IActionResult> GetAllShopType()
        {
            var result = await _companyUserInfoService.GetAllShopType();
            return Ok(result);
        }

        /// <summary>
        /// 修改店家密码（h5店家）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("pwd")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Shop)]
        public async Task<IActionResult> UpdateShopPwd([FromBody]UpdateShopPwdRequestDto dto)
        {
            var result = await _companyUserInfoService.UpdateShopPwd(UserId, dto);
            return Ok(result);
        }

        /// <summary>
        /// 修改店家信息（店家后台）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("UpdateShopInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Shop)]
        public async Task<IActionResult> UpdateShopInfo([FromBody]UpdateShopInfoRequestDto dto)
        {
            var result = await _companyUserInfoService.UpdateShopInfo(UserId, dto);
            return Ok(result);
        }

        /// <summary>
        /// 审核店家
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="status"></param>
        [HttpGet]
        [Route("ExamineShop")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> ExamineShop(int shopId, int status)
        {
            var result = await _companyUserInfoService.ExamineShop(shopId, status);
            return Ok(result);
        }

        /// <summary>
        /// 重置店家密码（管理员后台）
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="status"></param>
        [HttpGet]
        [Route("ResetShopPassword")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> ResetShopPassword(int shopId)
        {
            var result = await _companyUserInfoService.ResetShopPassword(shopId);
            return Ok(result);
        }


        /// <summary>
        /// 获取微信用户信息（商户）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("getWeiXinUserInfo")]
        [UnAuthorize]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<GetShopWeiXinUserInfo>))]
        public async Task<IActionResult> GetWeiXinUserInfo(string code)
        {
            ApiResult<GetShopWeiXinUserInfo> result = new ApiResult<GetShopWeiXinUserInfo>();
            result.IsSuccess = false;
            var tokenResult = await _weiXinService.GetAccessToken(code);
            if (tokenResult.IsSuccess)
            {
                var user = await _weiXinService.GetWXOAuthUserInfo(tokenResult.Data.access_token, tokenResult.Data.openid);
                if (user.IsSuccess)
                {
                    LogHelper.WriteLog(JsonConvert.SerializeObject(user.Data));
                    result.IsSuccess = true;
                    result.Data = new GetShopWeiXinUserInfo();
                    result.Data.wXOAuthUserInfo = user.Data;
                    var item = await _companyUserInfoService.GetCompanyUserInfoByOpenId(user.Data.openid);
                    if (item.Data == null)
                    {
                        result.Data.isRegister = false;
                    }
                    else
                    {
                        result.Data.isRegister = true;
                        result.Data.userInfoDto = item.Data;
                    }
                    return Ok(result);
                }
                else
                {
                    result.Message = user.Message;
                    return Ok(result);
                }
            }
            else
            {
                result.Message = tokenResult.Message;
                return Ok(result);
            }
        }


        /// <summary>
        ///修改管理员密码
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="status"></param>
        [HttpGet]
        [Route("UpdateAdminPassword")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> UpdateAdminPassword(string newPwd)
        {
            var result = await _companyUserInfoService.UpdateAdminPassword(UserId, newPwd);
            return Ok(result);
        }


        /// <summary>
        ///删除商户
        /// </summary>
        /// <param name="userId"></param>
        [HttpGet]
        [Route("DeleteCompanyUserInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> DeleteCompanyUserInfo(int userId)
        {
            var result = await _companyUserInfoService.DeleteCompanyUserInfo(userId);
            return Ok(result);
        }


        /// <summary>
        /// 获取微信用户信息（商户）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        //[HttpPost]
        //[Route("GetWeiXinUserInfoTest")]
        //[UnAuthorize]
        //[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<GetShopWeiXinUserInfo>))]
        //public async Task<IActionResult> GetWeiXinUserInfoTest(WXOAuthUserInfo info)
        //{
        //    ApiResult<GetShopWeiXinUserInfo> result = new ApiResult<GetShopWeiXinUserInfo>();
        //    result.Data = new GetShopWeiXinUserInfo();
        //    result.IsSuccess = false;
        //    var item = await _companyUserInfoService.GetCompanyUserInfoByOpenId(info.openid);
        //    if (item.Data == null)
        //    {
        //        result.Data.isRegister = false;
        //    }
        //    else
        //    {
        //        result.Data.isRegister = true;
        //        result.Data.userInfoDto = item.Data;
        //    }
        //    return Ok(result);

        //}
    }
}